package com.thread.chapter2;

public class Demo212 extends Thread {

    private HasSelfPrivateNum numRef;
    private String threadName;

    public Demo212(HasSelfPrivateNum numRef, String threadName) {
        this.numRef = numRef;
        this.threadName = threadName;
        System.out.println("调用构造方法线程:" + currentThread().getName());
    }

    @Override
    public void run() {
        super.run();
        System.out.println("当前执行线程:" + currentThread().getName());
        currentThread().setName(threadName);
        System.out.println("当前执行线程重命名:" + currentThread().getName());
        numRef.addI(currentThread().getName());
    }

    /*实例变量非线程安全例子,线程a和b都修改实例numRef的变量num,但是a打印结果是b修改后的造成非线程安全
     * 解决方法: 修改方法addI添加synchronized
     * */

    public static void main(String[] args) {
        HasSelfPrivateNum numRef = new HasSelfPrivateNum();
        Demo212 a = new Demo212(numRef, "a");
        Demo212 b = new Demo212(numRef, "b");
        a.start();
        b.start();
    }
}
